<template>
  <el-upload action="#" list-type="picture-card" :auto-upload="false" v-model:file-list="fileList" :show-file-list="true" :on-change="handleFileChange">
    <el-icon><Plus /></el-icon>

    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
          >
            <el-icon><Download /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { upload } from '@/Api/newsApi'

import type { UploadFile } from 'element-plus'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const fileList = ref([]) // 存储上传的文件列表

// 定义事件，用于向父组件传递封面图片数据
const emit = defineEmits(['update:coverImage', 'update:coverFile'])

// 将文件转换为Base64格式
const fileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

// 处理文件变化，调用上传接口
const handleFileChange = async (file) => {
  if (file.raw) {
    try {
      // 先将文件转换为Base64用于显示
      const base64 = await fileToBase64(file.raw)
      
      // 使用FormData上传文件
      const formData = new FormData()
      formData.append('file', file.raw) // 添加文件
      formData.append('id', String(Date.now())) // 添加ID
      formData.append('filename', file.name) // 添加文件名
      
      console.log('上传文件信息:', {
        name: file.name,
        size: file.size,
        type: file.raw.type
      })
      
      // 使用axios直接上传，绕过upload接口的参数限制
      const response = await fetch('http://localhost:3000/file/upload', {
        method: 'POST',
        body: formData,
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token') || JSON.parse(localStorage.getItem('login') || '{}').access_token}`
        }
      })
      
      if (!response.ok) {
        throw new Error(`上传失败，状态码: ${response.status}`)
      }
      
      const result = await response.json()
      console.log('上传成功，响应数据:', result)
      
      // 传递文件名和Base64数据给父组件
      emit('update:coverFile', {
        name: file.name,
        data: base64
      })
    } catch (error) {
      console.error('上传图片失败:', error)
      // 上传失败时仍然传递Base64数据给父组件，以便显示
      try {
        const base64 = await fileToBase64(file.raw)
        emit('update:coverFile', {
          name: file.name,
          data: base64
        })
      } catch (err) {
        console.error('转换图片为Base64失败', err)
        emit('update:coverFile', null)
      }
    }
  }
}

// 监听文件列表变化，向父组件发送更新
watch(fileList, async (newList) => {
  if (newList.length > 0) {
    // 如果有文件，获取原始文件对象
    const file = newList[0].raw
    if (file) {
      try {
        // 将文件转换为Base64
        const base64 = await fileToBase64(file)
        // 传递文件名和Base64数据
        emit('update:coverFile', {
          name: file.name,
          data: base64
        })
      } catch (error) {
        console.error('转换图片为Base64失败', error)
        emit('update:coverFile', null)
      }
    } else {
      // 如果没有原始文件对象，传递null
      emit('update:coverFile', null)
    }
  } else {
    // 如果没有文件，传递null
    emit('update:coverFile', null)
  }
}, { deep: true })

const handleRemove = (file: UploadFile) => {
  // 从文件列表中移除文件
  const index = fileList.value.findIndex(item => item.uid === file.uid)
  if (index !== -1) {
    fileList.value.splice(index, 1)
  }
}

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const handleDownload = (file: UploadFile) => {
  console.log(file)
}
</script>
